package com.movie.controller;

import com.movie.model.Movie;
import com.movie.service.MovieService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/movies")
@CrossOrigin(origins = "http://localhost:8080")
public class MovieController {
    
    @Autowired
    private MovieService movieService;
    
    // 获取所有电影（无分页）
    @GetMapping
    public List<Movie> getAllMovies() {
        return movieService.getAllMovies();
    }
    
    // 获取所有电影（分页）
    @GetMapping("/page")
    public Page<Movie> getAllMovies(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "6") int size) {
        return movieService.getAllMovies(page, size);
    }
    
    @GetMapping("/{id}")
    public ResponseEntity<Movie> getMovieById(@PathVariable Long id) {
        Optional<Movie> movie = movieService.getMovieById(id);
        if (movie.isPresent()) {
            return ResponseEntity.ok(movie.get());
        } else {
            return ResponseEntity.notFound().build();
        }
    }
    
    @PostMapping
    public Movie createMovie(@RequestBody Movie movie) {
        return movieService.saveMovie(movie);
    }
    
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteMovie(@PathVariable Long id) {
        movieService.deleteMovie(id);
        return ResponseEntity.ok().build();
    }
    
    // 按类型获取电影（无分页）
    @GetMapping("/genre/{genre}")
    public List<Movie> getMoviesByGenre(@PathVariable String genre) {
        return movieService.getMoviesByGenre(genre);
    }
    
    // 按类型获取电影（分页）
    @GetMapping("/genre/{genre}/page")
    public Page<Movie> getMoviesByGenre(
            @PathVariable String genre,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "6") int size) {
        return movieService.getMoviesByGenre(genre, page, size);
    }
    
    // 搜索电影（无分页）
    @GetMapping("/search")
    public List<Movie> searchMovies(@RequestParam String title) {
        return movieService.searchMovies(title);
    }
    
    // 搜索电影（分页）
    @GetMapping("/search/page")
    public Page<Movie> searchMovies(
            @RequestParam String title,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "6") int size) {
        return movieService.searchMovies(title, page, size);
    }
    
    // 获取所有电影分类
    @GetMapping("/genres")
    public List<String> getAllGenres() {
        return movieService.getAllGenres();
    }
    
    // 初始化示例数据接口
    @PostMapping("/init")
    public ResponseEntity<String> initializeSampleData() {
        try {
            // 检查是否已有数据
            if (movieService.getAllMovies().size() > 0) {
                return ResponseEntity.ok("数据已存在，无需初始化");
            }
            
            // 添加示例电影数据
            Movie movie1 = new Movie(
                "The Shawshank Redemption",
                "Two imprisoned men bond over a number of years, finding solace and eventual redemption through acts of common decency.",
                "Drama",
                "Frank Darabont",
                1994,
                "https://example.com/shawshank.mp4",
                "https://m.media-amazon.com/images/M/MV5BNDE3ODcxYzMtY2YzZC00NmNlLWJiNDMtZDViZWM2MzIxZDYwXkEyXkFqcGdeQXVyNjAwNDUxODI@._V1_.jpg",
                9.3,
                142
            );
            
            Movie movie2 = new Movie(
                "The Godfather",
                "The aging patriarch of an organized crime dynasty transfers control of his clandestine empire to his reluctant son.",
                "Crime, Drama",
                "Francis Ford Coppola",
                1972,
                "https://example.com/godfather.mp4",
                "https://m.media-amazon.com/images/M/MV5BM2MyNjYxNmUtYTAwNi00MTYxLWJmNWYtYzZlODY3ZTk3OTFlXkEyXkFqcGdeQXVyNzkwMjQ5NzM@._V1_.jpg",
                9.2,
                175
            );
            
            Movie movie3 = new Movie(
                "The Dark Knight",
                "When the menace known as the Joker wreaks havoc and chaos on the people of Gotham, Batman must accept one of the greatest psychological and physical tests of his ability to fight injustice.",
                "Action, Crime, Drama",
                "Christopher Nolan",
                2008,
                "https://example.com/darkknight.mp4",
                "https://m.media-amazon.com/images/M/MV5BMTMxNTMwODM0NF5BMl5BanBnXkFtZTcwODAyMTk2Mw@@._V1_.jpg",
                9.0,
                152
            );
            
            Movie movie4 = new Movie(
                "Pulp Fiction",
                "The lives of two mob hitmen, a boxer, a gangster and his wife, and a pair of diner bandits intertwine in four tales of violence and redemption.",
                "Crime, Drama",
                "Quentin Tarantino",
                1994,
                "https://example.com/pulpfiction.mp4",
                "https://m.media-amazon.com/images/M/MV5BNGNhMDIzZTUtNTBlZi00MTRlLWFjM2ItYzViMjE3YzI5MjljXkEyXkFqcGdeQXVyNzkwMjQ5NzM@._V1_.jpg",
                8.9,
                154
            );
            
            Movie movie5 = new Movie(
                "Forrest Gump",
                "The presidencies of Kennedy and Johnson, the events of Vietnam, Watergate, and other historical events unfold through the perspective of an Alabama man with an IQ of 75.",
                "Drama, Romance",
                "Robert Zemeckis",
                1994,
                "https://example.com/forrestgump.mp4",
                "https://m.media-amazon.com/images/M/MV5BNWIwODRlZTUtY2U3ZS00Yzg1LWJhNzYtMmZiYmEyNmU1NjMzXkEyXkFqcGdeQXVyMTQxNzMzNDI@._V1_.jpg",
                8.8,
                142
            );
            
            Movie movie6 = new Movie(
                "Inception",
                "A thief who steals corporate secrets through the use of dream-sharing technology is given the inverse task of planting an idea into the mind of a C.E.O.",
                "Action, Adventure, Sci-Fi",
                "Christopher Nolan",
                2010,
                "https://example.com/inception.mp4",
                "https://m.media-amazon.com/images/M/MV5BMjAxMzY3NjcxNF5BMl5BanBnXkFtZTcwNTI5OTM0Mw@@._V1_.jpg",
                8.8,
                148
            );
            
            Movie movie7 = new Movie(
                "The Matrix",
                "A computer hacker learns from mysterious rebels about the true nature of his reality and his role in the war against its controllers.",
                "Action, Sci-Fi",
                "Lana Wachowski, Lilly Wachowski",
                1999,
                "https://example.com/thematrix.mp4",
                "https://m.media-amazon.com/images/M/MV5BNzQzOTk3OTAtNDQ0Zi00ZTVkLWI0MTEtMDllZjNkYzNjNTc4L2ltYWdlXkEyXkFqcGdeQXVyNjU0OTQ0OTY@._V1_.jpg",
                8.7,
                136
            );
            
            Movie movie8 = new Movie(
                "Goodfellas",
                "The story of Henry Hill and his life in the mob, covering his relationship with his wife Karen Hill and his mob partners Jimmy Conway and Tommy DeVito.",
                "Biography, Crime, Drama",
                "Martin Scorsese",
                1990,
                "https://example.com/goodfellas.mp4",
                "https://m.media-amazon.com/images/M/MV5BY2NkZjEzMDgtN2RjYy00YzM1LWI4ZmQtMjIwYjFjNmI3ZGEwXkEyXkFqcGdeQXVyNzkwMjQ5NzM@._V1_.jpg",
                8.7,
                146
            );
            
            movieService.saveMovie(movie1);
            movieService.saveMovie(movie2);
            movieService.saveMovie(movie3);
            movieService.saveMovie(movie4);
            movieService.saveMovie(movie5);
            movieService.saveMovie(movie6);
            movieService.saveMovie(movie7);
            movieService.saveMovie(movie8);
            
            return ResponseEntity.ok("成功初始化 " + movieService.getAllMovies().size() + " 部电影数据");
        } catch (Exception e) {
            return ResponseEntity.status(500).body("初始化失败: " + e.getMessage());
        }
    }
}